const financialService = require('../../../services/financial');
const calculator = require('../../../utils/calculator');

Page({
  data: {
    loading: true,
    products: [],
    searchValue: '',
    sortField: 'end_date',
    sortOrder: 'asc',
    filterType: 'all',
    list: [],
    filterVisible: false,
    sortVisible: false,
    // 筛选条件
    filter: {
      bankId: '',
      type: '',
      keyword: ''
    },
    // 排序条件
    sort: {
      field: 'create_time',
      order: 'desc'
    },
    // 银行列表
    banks: [
      { id: '', name: '全部' },
      { id: 'ICBC', name: '工商银行' },
      { id: 'ABC', name: '农业银行' },
      { id: 'BOC', name: '中国银行' },
      { id: 'CCB', name: '建设银行' },
      { id: 'CMBC', name: '民生银行' },
      { id: 'CEB', name: '光大银行' },
      { id: 'HXB', name: '华夏银行' },
      { id: 'CIB', name: '兴业银行' },
      { id: 'SPDB', name: '浦发银行' },
      { id: 'CMB', name: '招商银行' },
      { id: 'PAB', name: '平安银行' },
      { id: 'OTHER', name: '其他机构' }
    ],
    // 产品类型
    types: [
      { id: '', name: '全部' },
      { id: '定期存款', name: '定期存款' },
      { id: '结构性存款', name: '结构性存款' },
      { id: '大额存单', name: '大额存单' },
      { id: '理财产品', name: '理财产品' },
      { id: '基金', name: '基金' },
      { id: '股票', name: '股票' },
      { id: '债券', name: '债券' },
      { id: '保险', name: '保险' },
      { id: '其他', name: '其他' }
    ],
    // 排序选项
    sortOptions: [
      { field: 'create_time', name: '创建时间' },
      { field: 'profit', name: '总收益' },
      { field: 'arr', name: '年化收益率' },
      { field: 'money', name: '投资金额' },
      { field: 'holding_days', name: '持有天数' }
    ]
  },

  onLoad() {
    this.loadData();
  },

  onPullDownRefresh() {
    this.loadData();
  },

  onReachBottom() {
    // 加载更多数据
    if (!this.data.loading && this.data.hasMore) {
      this.loadMoreData();
    }
  },

  async loadData() {
    try {
      this.setData({ loading: true });
      const products = await financialService.getFinancialList({
        search: this.data.searchValue,
        sortField: this.data.sortField,
        sortOrder: this.data.sortOrder,
        type: this.data.filterType === 'all' ? null : this.data.filterType
      });

      // 新增：对日期字段进行格式化
      const formattedProducts = products.map(item => ({
        ...item,
        // 假设产品数据中有 `buyDate` 和 `endDate` 字段需要格式化
        formattedBuyDate: this.formatDate(item.buyDate),
        formattedEndDate: this.formatDate(item.endDate)
      }));

      this.setData({
        products: formattedProducts, // 存储格式化后的数据
        loading: false,
        hasMore: formattedProducts.length >= 20
      });
    } catch (error) {
      console.error('加载数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    } finally {
      wx.stopPullDownRefresh();
    }
  },

  async loadMoreData() {
    if (this.data.loading) return;

    try {
      this.setData({ loading: true });
      const lastItem = this.data.products[this.data.products.length - 1];
      const moreProducts = await financialService.getFinancialList({
        search: this.data.searchValue,
        sortField: this.data.sortField,
        sortOrder: this.data.sortOrder,
        type: this.data.filterType === 'all' ? null : this.data.filterType,
        lastId: lastItem._id
      });

      this.setData({
        products: [...this.data.products, ...moreProducts],
        loading: false,
        hasMore: moreProducts.length >= 20
      });
    } catch (error) {
      console.error('加载更多数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    }
  },

  onSearch(e) {
    this.setData({
      searchValue: e.detail.value
    }, () => {
      this.loadData();
    });
  },

  onSort(e) {
    const { field } = e.currentTarget.dataset;
    const newOrder = this.data.sortField === field && this.data.sortOrder === 'asc' ? 'desc' : 'asc';
    
    this.setData({
      sortField: field,
      sortOrder: newOrder
    }, () => {
      this.loadData();
    });
  },

  onFilter(e) {
    const { type } = e.currentTarget.dataset;
    this.setData({
      filterType: type
    }, () => {
      this.loadData();
    });
  },

  navigateToDetail(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/financial/detail/detail?id=${id}`
    });
  },

  navigateToAdd() {
    wx.navigateTo({
      url: '/pages/financial/add/add'
    });
  },

  // 显示筛选面板
  showFilter() {
    this.setData({ filterVisible: true });
  },

  // 显示排序面板
  showSort() {
    this.setData({ sortVisible: true });
  },

  // 处理筛选条件变化
  handleFilterChange(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    this.setData({
      [`filter.${field}`]: value
    });
  },

  // 处理排序条件变化
  handleSortChange(e) {
    const { field } = e.currentTarget.dataset;
    const currentOrder = this.data.sort.order;
    
    this.setData({
      sort: {
        field,
        order: field === this.data.sort.field ? 
          (currentOrder === 'desc' ? 'asc' : 'desc') : 'desc'
      }
    });

    this.loadData();
  },

  // 应用筛选条件
  applyFilter() {
    this.setData({ filterVisible: false });
    this.loadData();
  },

  // 重置筛选条件
  resetFilter() {
    this.setData({
      filter: {
        bankId: '',
        type: '',
        keyword: ''
      }
    });
  },

  onLoad() {
    this.getFinancialList();
  },

  // 获取理财列表（修改后）
  async getFinancialList() {
    const res = await financialService.getFinancialList();
    // 处理数据：转化类型 + 补充默认收益率
    const formattedList = res.map(item => ({
      ...item,
      // 类型转化：使用 TYPE_MAP 映射，无匹配时显示"其他"
      // type: this.data.TYPE_MAP[item.type] || '其他',
      // 收益率处理：无值时默认0.00（保留两位小数）
      profit_rate: item.profit_rate ? Number(item.profit_rate).toFixed(2) : '0.00'
    }));
    this.setData({
      products: formattedList
    });
  },

  // 日期格式化函数（修改后）
  formatDate(dateStr) {
    if (!dateStr) return ''; // 处理空值
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return ''; // 处理无效日期
    
    // 使用UTC方法获取年、月、日（避免本地时区干扰）
    const year = date.getUTCFullYear();
    const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // 月份从0开始，+1
    const day = String(date.getUTCDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  }
})